//
//  ViewController.m
//  ExportTableTool
//
//  Created by apple on 2019/4/15.
//  Copyright © 2019年 apple. All rights reserved.
//

#import "ViewController.h"
#import "Data.h"
#import "HGBookmark.h"

@interface ViewController()<NSTextFieldDelegate>

// 文件路径
@property (nonatomic, copy) NSString *filePath;

// 导出路径
@property (nonatomic, copy) NSString *exportFilePath;

// 路径输入框
@property (weak) IBOutlet NSTextField *sourcePathTextField;

// 导出路径输入框
@property (weak) IBOutlet NSTextField *exportPathTextField;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [Data openSql];
    
    self.sourcePathTextField.stringValue = [Data getDataForKey:@"filePath"];
    self.exportPathTextField.stringValue = [Data getDataForKey:@"exportFilePath"];
    
    self.sourcePathTextField.delegate = self;
    self.exportPathTextField.delegate = self;
    
    self.sourcePathTextField.tag = 100;
    self.exportPathTextField.tag = 200;
}

#pragma mark - NSTextDelegate

- (void)controlTextDidChange:(NSNotification *)notification{
    NSTextView *textView = notification.userInfo[@"NSFieldEditor"];
    NSString *string = textView.string;
    
    NSTextField *sender = notification.object;
    
    switch (sender.tag) {
        case 100:
            self.filePath = string;
            break;
        case 200:
            self.exportFilePath = string;
            break;
    }
}

#pragma mark - action

// 选择文件
- (IBAction)choseFilePath:(NSButton *)sender{
    NSOpenPanel *openPanel = [NSOpenPanel openPanel];
    [openPanel setCanChooseFiles:YES];
    [openPanel setCanChooseDirectories:YES];
    
    NSWindow *window = [[NSApplication sharedApplication] keyWindow];
    [openPanel beginSheetModalForWindow:window completionHandler:^(NSModalResponse returnCode) {
        if (returnCode == 1) {
            NSURL *fileUrl = [[openPanel URLs] objectAtIndex:0];
            NSString *filePath = [[fileUrl.absoluteString componentsSeparatedByString:@"file://"] lastObject];
            filePath = [filePath stringByRemovingPercentEncoding];
            
            [[HGBookmark defaultShareBookmark] saveOpenFileToBookmarkWithFilePath:filePath];
            
            self.sourcePathTextField.stringValue = filePath;
            self.filePath = filePath;
            NSLog(@"fileContext = %@",filePath);
        }
    }];
}

// 导出目录
- (IBAction)exportFilePath:(NSButton *)sender {
    NSOpenPanel *openPanel = [NSOpenPanel openPanel];
    [openPanel setCanChooseFiles:YES];
    [openPanel setCanChooseDirectories:YES];
    
    NSWindow *window = [[NSApplication sharedApplication] keyWindow];
    [openPanel beginSheetModalForWindow:window completionHandler:^(NSModalResponse returnCode) {
        if (returnCode == 1) {
            NSURL *fileUrl = [[openPanel URLs] objectAtIndex:0];
            NSString *filePath = [[fileUrl.absoluteString componentsSeparatedByString:@"file://"] lastObject];
            filePath = [filePath stringByRemovingPercentEncoding];
            
            [[HGBookmark defaultShareBookmark] saveOpenFileToBookmarkWithFilePath:filePath];
            
            self.exportPathTextField.stringValue = filePath;
            self.exportFilePath = filePath;
            NSLog(@"fileContext = %@",filePath);
        }
    }];
}

// 开始
- (IBAction)startAction:(id)sender {
    [[HGBookmark defaultShareBookmark] BookmarkStartAccessingSecurityScopedResourceWithFilePath:self.filePath];
    [[HGBookmark defaultShareBookmark] BookmarkStartAccessingSecurityScopedResourceWithFilePath:self.exportFilePath];
    
    BOOL isDirectory = NO;
    [[NSFileManager defaultManager] fileExistsAtPath:self.filePath isDirectory:&isDirectory];
    
    if (isDirectory) { // 是否是文件夹
        // 文件管理器
        NSFileManager *manager = [NSFileManager defaultManager];
        
        // 枚举器
        NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:self.filePath];
        
        // 遍历文件夹内部所有xlsx文档 ，读取内容
        NSString *filename;
        
        while (filename = [direnum nextObject]) {
            
            if ([[filename pathExtension] isEqualTo:@"xlsx"]) {
                NSString *path = [NSString stringWithFormat:@"%@/%@",self.filePath,filename];
                [self recodeExcelForPath:path];
            }
        }
    }else{
        [self recodeExcelForPath:self.filePath];
    }
}

/**
 保存文件
 
 @param array 文件数据
 @param fileName 路径
 */
- (void)saveArray:(NSArray*)array fileName:(NSString *)fileName{
    NSData *data = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:nil];
    
    NSArray *nameArray = [self.filePath componentsSeparatedByString:@"/"];
    NSString *name = nameArray.lastObject;
    name = [name stringByReplacingOccurrencesOfString:@".xlsx" withString:@""];
    NSString *savePath = [NSString stringWithFormat:@"%@/%@.json",self.exportFilePath, fileName];
    
    NSFileManager *manager = [NSFileManager defaultManager];
    
    [manager fileExistsAtPath:savePath];
    [manager createFileAtPath:savePath contents:data attributes:nil];
}

/**
 获取表数据

 @param filePath 表路径
 */
- (void)recodeExcelForPath:(NSString *)filePath{
    BRAOfficeDocumentPackage *spreadsheet = [BRAOfficeDocumentPackage open:filePath];
    NSArray *worksheets = [[spreadsheet workbook] worksheets];
    
    for (BRAWorksheet *sheet in worksheets) {
        NSArray *lins = sheet.rows;
        
        // 获取的是表头的字段(key)
        BRARow *keyLine = lins[1];
        NSArray *key = keyLine.cells;
        
        NSMutableArray *array = [NSMutableArray array];
        
        for (NSUInteger index = 2; index < lins.count; index++) {
            BRARow *line = lins[index];
            
            // 获取的内容
            NSArray *a = line.cells;
            
            // 防止数组越界
            if (a.count < key.count) {
                continue;
            }
            
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            
            for (int i = 0; i < key.count; i ++) {
                // 组成字典数组
                NSString *keyString = [key[i] stringValue];
                
                if (keyString.length > 0) {
                    BRACell *itemCell = a[i];
                    [dic setObject:[itemCell getValue]
                            forKey:keyString];
                }
            }
            
            [array addObject:dic];
        }
        
        NSArray *nameArray = [filePath componentsSeparatedByString:@"/"];
        NSString *name = nameArray.lastObject;
        name = [name stringByReplacingOccurrencesOfString:@".xlsx" withString:@""];
        
        [self saveArray:array fileName:[NSString stringWithFormat:@"%@_%@", name, sheet.name]];
    }
}

#pragma mark - getter/setter

@synthesize filePath = _filePath;
@synthesize exportFilePath = _exportFilePath;

- (void)setFilePath:(NSString *)filePath{
    _filePath = filePath;
    
    [Data saveData:filePath key:@"filePath"];
}

- (void)setExportFilePath:(NSString *)exportFilePath{
    _exportFilePath = exportFilePath;
    
    [Data saveData:exportFilePath key:@"exportFilePath"];
}

- (NSString *)filePath{
    if (!_filePath) {
        _filePath = self.sourcePathTextField.stringValue;
    }
    return _filePath;
}

- (NSString *)exportFilePath{
    if (!_exportFilePath) {
        _exportFilePath = self.exportPathTextField.stringValue;
    }
    return _exportFilePath;
}

- (void)dealloc{
    [Data closeSql];
}

@end

@implementation BRACell (Value)

/**
 获取相应类型的数据
 
 @return 相应的类型数据
 */
- (NSObject *)getValue{
    
    NSObject *result = self;
    
    switch (self.type) {
        case BRACellContentTypeBoolean:
            result = @([self boolValue]);
            break;
        case BRACellContentTypeNumber:
        case BRACellContentTypeUnknown:
            result = @([self floatValue]);
            break;
            
        default:
            result = [self stringValue];
            break;
    }
    
    return result;
}

@end
